import useStaff from '@/composable/staff';
import { ref, onMounted, watch } from 'vue';
import { useI18n } from 'vue-i18n';
import usePagination from '@/composable/pagination';

export default function useStaffList() {

  const PAGESIZE = 5;

  const data = ref([]);
  const onlyDepartment = ref(true);

  const { t } = useI18n();
  const { getStaffByPage } = useStaff();
  const { loading, pagination } = usePagination(data, PAGESIZE, {
    currentPageParamName: 'currentPage',
    totalParamName: 'total',
  });

  onMounted(() => fetchData(1));
  watch(onlyDepartment, () => {
    fetchData(1)
  });

  const fetchData = (page) => {
    loading.value = true;
    getStaffByPage(page, PAGESIZE, onlyDepartment.value).then(res => {
      if (res.data.code == 200) {
        data.value = res.data.data.list;
        data.value['currentPage'] = page;
        data.value['total'] = res.data.data.total;
        console.log("获取成功")
      } else {
        console.log(`获取失败：${res.data.message}`);
      }
    }).catch(e => {
        console.log(`获取失败：${e}`);
    }).finally(()=>{
        loading.value = false;
        console.log(pagination.value);
    });
  }


  const handleTableChange = (
    pag: { pageSize: number; current: number },
    filters: any,
    sorter: any,
  ) => {
    fetchData(pag.current);
  };


  const columns = [
    {
      title: t('table.staff.name'),
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: t('table.staff.gender'),
      dataIndex: 'gender',
      key: 'gender',
    },
    {
      title: t('table.staff.phone'),
      dataIndex: 'phone',
      key: 'phone',
    },
    {
      title: t('table.staff.department'),
      dataIndex: 'department.name',
      key: 'departmentname',
    },
    {
      title: t('table.staff.state'),
      dataIndex: 'state',
      key: 'state',
    },
    {
      title: t('table.staff.note'),
      dataIndex: 'note',
      key: 'note',
      ellipsis: true,
    },
    {
      title: t('table.action'),
      key: 'action',
      fixed: 'right',
      width: 200
    }
  ]

  const reloadTableData = () => fetchData(pagination.value.current);

  return { onlyDepartment, columns, data, pagination, loading, handleTableChange, reloadTableData }
}